<template>
  <el-button type="primary" @click="toAdd">
    添加
  </el-button>
  <el-divider direction="vertical"></el-divider>
  <el-button :icon="Refresh" :loading="loading" @click="refreshTable">
    <span>刷新</span>
  </el-button>

  <el-divider style="margin-top: 8px"></el-divider>
  <el-form
      :label-position="'top'"
      label-width="100px"
      :model="conditionForm"
      inline
  >
    <el-form-item label="关键字">
      <el-input v-model="conditionForm.searchText" @keydown.enter="getAll" placeholder="Key words"/>
    </el-form-item>
    <el-form-item label="分类:" prop="categoryId">
      <el-select v-model="conditionForm.categoryId" filterable clearable
                 placeholder="Select category" @clear="conditionForm.categoryId=null">
        <el-option
            v-for="item in categories"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId"
            :disabled="!item.isUse"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="标签（多选）:">
      <el-select v-model="conditionForm.tagIdList"
                 multiple
                 clearable
                 filterable
                 placeholder="Select Tag">
        <el-option
            v-for="item in tags"
            :key="item.tagId"
            :label="item.tagName"
            :value="item.tagId"
            :disabled="!item.isUse"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="置顶:">
      <el-radio-group v-model="conditionForm.isTop">
        <el-radio :label="null">全部</el-radio>
        <el-radio :label="false">否</el-radio>
        <el-radio :label="true">是</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="发布日期范围">
      <el-col :span="11">
        <el-date-picker
            v-model="conditionForm.beginCreateTime"
            type="date"
            placeholder="Pick a start date"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-col>
      <el-col :span="2" style="text-align: center;">
        <span>-</span>
      </el-col>
      <el-col :span="11">
        <el-date-picker
            v-model="conditionForm.endCreateTime"
            placeholder="Pick a end time"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD 23:59:59"
        />
      </el-col>
    </el-form-item>
    <el-form-item label="排序">
      <el-switch
          v-model="conditionForm.orderBy"
          active-value="asc"
          active-text="id 升序"
          inactive-value="desc"
          inactive-text="id 降序"
      />
    </el-form-item>
    <el-form-item label="-">
      <el-button type="primary" @click="getAll">查询</el-button>
    </el-form-item>
  </el-form>

  <el-divider style="margin-top: 8px"></el-divider>
  <el-table :data="tableData" stripe style="width: 100%">
    <el-table-column prop="blogId" label="Id" width="70" sortable/>
    <el-table-column label="作者" width="130">
      <template #default="scope">
        <div style="display:flex;align-items: center;text-align: center">
          <el-avatar size="small" :src="scope.row.author.headImg"></el-avatar>
          <span style="margin-left: 5px">{{ scope.row.author.userNickName }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="blogTitle" label="标题" min-width="220">
      <template #default="scope">
        <el-link @click="view(scope.row)">{{ scope.row.blogTitle }}</el-link>
      </template>
    </el-table-column>
    <el-table-column prop="blogImg" label="主图" width="80">
      <template #default="scope">
        <el-popover :width="280" placement="right">
          <template #reference>
            <el-avatar shape="square" size="large" :src="scope.row.blogImg"
                       style="border: 1px solid #454555"/>
          </template>
          <img :src="scope.row.blogImg" style="width: 250px">
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column prop="blogCategoryName" label="分类"
                     :filters=categoriesFilter
                     :filter-method="categoryFilterHandler"
                     :filter-multiple="false"
                     width="150"/>
    <el-table-column prop="tags" label="标签" width="100">
      <template #default="scope">
        <p v-for="tag in scope.row.tags" :style="{color:tag.tagColor}">{{ tag.tagName }}</p>
      </template>
    </el-table-column>
    <el-table-column prop="blogViews" label="浏览量" width="100" sortable/>
    <el-table-column prop="isTop" label="是否置顶"
                     :filters="[{text:'置顶',value:true},{text:'默认',value:false}]"
                     :filter-multiple="false"
                     :filter-method="booleanFilterHandler"
                     width="100">
      <template #default="scope">
        <el-tag :type="scope.row.isTop?'success':'info'">{{ scope.row.isTop ? '置顶' : '默认' }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="blogStatus" label="发布状态"
                     :filters="[{text:'已发布',value:true},{text:'草稿',value:false}]"
                     :filter-multiple="false"
                     :filter-method="booleanFilterHandler"
                     width="100">
      <template #default="scope">
        <el-tag :type="scope.row.blogStatus?'success':'info'">{{ scope.row.blogStatus ? '已发布' : '草稿' }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="enableComment" label="允许评论"
                     :filters="[{text:'允许',value:true},{text:'不允许',value:false}]"
                     :filter-multiple="false"
                     :filter-method="booleanFilterHandler"
                     width="100">
      <template #default="scope">
        <el-tag :type="scope.row.enableComment?'success':'info'">{{
            scope.row.enableComment ? '允许' : '不允许'
          }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="isDeleted" label="是否删除"
                     :filters="[{text:'是',value:true},{text:'否',value:false}]"
                     :filter-multiple="false"
                     :filter-method="booleanFilterHandler"
                     width="100">
      <template #default="scope">
        <el-tag :type="scope.row.isDeleted?'info':'success'">{{ scope.row.isDeleted ? '已删除' : '正常' }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="时间" width="240">
      <template #default="scope">
        <p>创建：{{ scope.row.createTime }}</p>
        <p>发布：{{ scope.row.releaseTime }}</p>
        <p>修改：{{ scope.row.updateTime }}</p>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="80">
      <template #default="scope">
        <el-popconfirm title="确定要彻底删除这篇文章吗?" @confirm="deleteBlog(scope.row.blogId)">
          <template #reference>
            <el-link type="danger">
              <el-icon>
                <Delete/>
              </el-icon>
            </el-link>
          </template>
        </el-popconfirm>
        <el-divider direction="vertical"></el-divider>
        <el-link type="primary" @click="editBlog(scope.row.blogId)">
          <el-icon>
            <Edit/>
          </el-icon>
        </el-link>
      </template>
    </el-table-column>
  </el-table>

  <el-divider></el-divider>
  <!--分页-->
  <div style="display: flex;">
    <el-pagination
        v-model:current-page="conditionForm.pageNum"
        v-model:page-size="conditionForm.pageSize"
        :page-sizes="[15, 30, 45, 60]"
        :small="true"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin: auto;"
    />
  </div>

  <el-dialog v-model="dialogVisible"
             :title="viewBlog.blogTitle"
             width="60%"
             :before-close="handleClose">
    <v-md-preview :text="viewBlog.blogContent"></v-md-preview>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="editBlog(viewBlog.blogId)">
          修改
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script>
import {Refresh, Search} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";

export default {
  name: "ArticleManage",
  created() {
    this.uploadCategories()
    this.uploadTags()
    this.getAll()
  },
  computed: {
    categoriesFilter() {
      let filter = []
      this.categories.forEach(item => {
        filter.push({text: item.categoryName, value: item.categoryId})
      })
      return filter
    }
  },
  data() {
    return {
      Refresh, Search,
      dialogVisible: false,
      viewBlog: {
        blogTitle: "",
        blogContent: "",
      },
      conditionForm: {
        pageSize: 15,
        pageNum: 1,
        searchText: '',
        categoryId: null,
        tagIdList: null,
        isTop: null,
        beginCreateTime: null,
        endCreateTime: null,
        orderBy: "desc"
      },
      loading: false,
      tableData: [],
      categories: [],
      tags: [],
      total: 0,
    }
  },
  methods: {
    toAdd() {
      this.$router.push({name: 'editBlog', params: {id: 0}})
    },
    async uploadCategories() {
      let {data: categories} = await this.$http.get('/api/category/getAllCategories')
      this.categories = categories
    },
    async uploadTags() {
      let {data: tags} = await this.$http.get('/api/tag/getAllTags')
      this.tags = tags
    },
    async getAll() {
      let {data: result} = await this.$http.post('/api/blog/condition', this.conditionForm)
      this.tableData = result.dataMap.page.records
      // this.current = result.dataMap.page.current
      this.conditionForm.pageNum = result.dataMap.page.current
      this.total = result.dataMap.page.total
      // this.size = result.dataMap.page.size
      this.conditionForm.pageSize = result.dataMap.page.size
    },
    refreshTable() {
      this.loading = true
      this.getAll()
      this.loading = false
    },
    editBlog(id) {
      this.$router.push({name: "editBlog", params: {id: id}})
    },
    async deleteBlog(blogId) {
      this.loading = true
      let {data: result} = await this.$http.get("/api/blog/deleteBlog", {
        params: {
          blogId: blogId,
        }
      })
      if (result.code !== 200) {
        ElMessage.error({
          showClose: true, message: result.msg
        })
      } else {
        ElMessage.success({
          showClose: true, message: result.msg
        })
      }
      this.refreshTable()
    },
    // 打开预览框
    view(blog) {
      this.viewBlog = blog
      this.dialogVisible = true
    },
    // 关闭弹出框
    handleClose() {
      this.$data.viewBlog = this.$options.data().viewBlog
      this.dialogVisible = false
    },
    // 类型筛选方法
    categoryFilterHandler(value, row) {
      return row.blogCategoryId === value
    },
    // bool类型筛选
    booleanFilterHandler(value, row, column) {
      let property = column['property']
      return row[property] === value
    },
    // 分页大小改变
    handleSizeChange() {
      this.refreshTable()
    },
    // 分页页数改变
    handleCurrentChange() {
      this.refreshTable()
    },
  }
}
</script>

<style scoped>

</style>